package com.dotstone.chipism.view;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.Room;

//public class CircleView extends SurfaceView implements Callback, Runnable {
public class CircleView extends SurfaceView implements Callback {
	private SurfaceHolder mHolder;
	/**
	 * 与SurfaceHolder绑定的Canvas
	 */
	private Canvas mCanvas;
	/**
	 * 用于绘制的线程
	 */
	/**
	 * 线程的控制开关
	 */

	/**
	 * 抽奖的文字
	 */
	// private String[] mStrs;
	private List<Room> mRooms = new ArrayList<Room>();
	private List<Room> mShowRooms = new ArrayList<Room>();
	private int startCount = 0;
	private int endCount = 0;
	// private List<MyView> myViews = new ArrayList<MyView>();
	/**
	 * 每个盘块的颜色
	 */
	/**
	 * 与文字对应的图片
	 */

	/**
	 * 与文字对应图片的bitmap数组
	 */
	/**
	 * 盘块的个数
	 */
	private int mItemCount = 6;

	/**
	 * 绘制盘块的范围
	 */
	private RectF mRange = new RectF();
	/**
	 * 圆的直径
	 */
	private int mRadius;
	/**
	 * 绘制盘快的画笔
	 */
	private Paint mArcPaint;

	/**
	 * 绘制文字的画笔
	 */
	private Paint mTextPaint;
	private Paint mTextPaint1;
	private int h;
	/**
	 * 滚动的速度
	 */
	private double mSpeed;
	private volatile float mStartAngle = (float) 247.5;
	/**
	 * 是否点击了停止
	 */
	private boolean isShouldEnd;

	/**
	 * 控件的padding，这里我们认为4个padding的值一致，以paddingleft为标准
	 */
	private int mCenterw;
	private int mCenterh;

	private int mPadding;

	private Bitmap mBgBitmap = BitmapFactory.decodeResource(getResources(),
			R.drawable.btn_018_2x);

	private float mTextSize = TypedValue.applyDimension(
			TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics());
	private float mSelectTextSize = TypedValue.applyDimension(
			TypedValue.COMPLEX_UNIT_SP, 22, getResources().getDisplayMetrics());
	private boolean firstTouch = true;

	public CircleView(Context context) {
		this(context, null);
	}

	public CircleView(Context context, AttributeSet attrs) {
		super(context, attrs);

		mHolder = getHolder();
		mHolder.addCallback(this);

		setFocusable(true);
		setFocusableInTouchMode(true);
		this.setKeepScreenOn(true);

	}

	// public void setStrs(String[] mStrs) {
	// this.mStrs = mStrs;
	// mItemCount = mStrs.length;
	// }

	public void setData(List<Room> mRooms) {
		Log.i("wmy", "加载数据" + mRooms.size());
		this.mRooms = mRooms;
		if (mRooms.size() > 6) {
			mItemCount = 6;
			// int differ = mDevices.size() - 8;
			// if (differ % 2 == 0) {
			startCount = 0;
			endCount = 6;
			mShowRooms.clear();
			for (int i = startCount; i < startCount + 6; i++) {
				mShowRooms.add(mRooms.get(i));
			}
		} else {
			mShowRooms = mRooms;
			mItemCount = mShowRooms.size();
		}
		draw();
	}

	/**
	 * 设置控件为正方形
	 */
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);

		int width = Math.min(getMeasuredWidth(), getMeasuredHeight());
		// 获取圆形的直径
		mRadius = width - getPaddingLeft() - getPaddingRight();
		// padding值
		mPadding = getPaddingLeft();
		// 中心点
		mCenterw = width / 2;
		mCenterh = width / 2;
		setMeasuredDimension(width, width);
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// 初始化绘制圆弧的画笔
		mArcPaint = new Paint();
		mArcPaint.setAntiAlias(true);
		mArcPaint.setDither(true);
		// 初始化绘制文字的画笔
		mTextPaint = new Paint();
		mTextPaint.setColor(0xFFFF0000);
		mTextPaint.setTextSize(mTextSize);

		mTextPaint1 = new Paint();
		mTextPaint1.setColor(0xFFffffff);
		mTextPaint1.setTextSize(mSelectTextSize);
		// 圆弧的绘制范围
		mRange = new RectF(getPaddingLeft(), getPaddingLeft(), mRadius
				+ getPaddingLeft(), mRadius + getPaddingLeft());
		draw();
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {

	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return true;
	}

	private boolean isFling;
	private AutoFlingRunnable mFlingRunnable;
	/**
	 * 记录上一次的x，y坐标
	 */
	private float mLastX;
	private float mLastY;
	private long mDownTime;
	private long lastTime;
	private long currentTime;
	private long mUpTime;
	private float mTmpAngle;
	private int mFlingableValue = FLINGABLE_VALUE;
	private static final int FLINGABLE_VALUE = 300;
	private static final int NOCLICK_VALUE = 3;
	private float lastDegree;
	private float firstDegree;

	private class AutoFlingRunnable implements Runnable {

		private float angelPerSecond;

		public AutoFlingRunnable(float velocity) {
			this.angelPerSecond = velocity;
		}

		public void run() {
			// 如果小于20,则停止
			if ((int) Math.abs(angelPerSecond) < 20) {
				isFling = false;
				return;
			}
			isFling = true;
			// 不断改变mStartAngle，让其滚动，/30为了避免滚动太快
			mStartAngle += (angelPerSecond / 60);
			// 逐渐减小这个值
			angelPerSecond /= 1.0666F;
			postDelayed(this, 30);
			// 重新布局
			requestLayout();
		}
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		float x = event.getX();
		float y = event.getY();
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:

			mLastX = x;
			mLastY = y;
			mDownTime = System.currentTimeMillis();
			lastTime = System.currentTimeMillis();
			mTmpAngle = 0;
			lastDegree = detaDegree(x, y);
			if (firstTouch) {
				firstDegree = detaDegree(x, y);
				firstTouch = false;
			}
			// 如果当前已经在快速滚动
			if (isFling) {
				// 移除快速滚动的回调
				removeCallbacks(mFlingRunnable);
				isFling = false;
				return true;
			}

			break;
		case MotionEvent.ACTION_MOVE:
			currentTime = System.currentTimeMillis();
			/**
			 * 获得开始的角度
			 */
			float start = getAngle(mLastX, mLastY);
			/**
			 * 获得当前的角度
			 */
			float end = getAngle(x, y);
			if (mItemCount == 8) {
				float start1 = detaDegree(mLastX, mLastY);
				float end1 = detaDegree(x, y);

				if (end1 > start1) { // 顺时针滑动
					if (Math.abs(end1 - firstDegree) > 45) {
						firstDegree = end1;
						startCount++;
						endCount++;
						Log.i("wmy", "顺时针滑过了45度  " + startCount + " "
								+ endCount);
						// for (int i = 0; i < mItemCount; i++) {
						// mShowDevices.get(i).setName(
						// mDevices.get((startCount + i) % mItemCount)
						// .getName());
						// }
					}
				} else {
					if (Math.abs(start1 - firstDegree) > 45) {
						firstDegree = start1;
						startCount--;
						endCount--;
						Log.i("wmy", "逆时针滑过了45度  " + startCount + " "
								+ endCount);
					}
				}
			}
			if ((currentTime - mDownTime) > 200) {
				draw();
			}
			if (getQuadrant(x, y) == 1 || getQuadrant(x, y) == 4) {
				mStartAngle += end - start;
				mTmpAngle += end - start;
			} else
			// 二、三象限，色角度值是付值
			{
				mStartAngle += start - end;
				mTmpAngle += start - end;
			}
			// 重新布局
			requestLayout();

			mLastX = x;
			mLastY = y;

			break;
		case MotionEvent.ACTION_UP:
			mUpTime = System.currentTimeMillis();
			if (mUpTime - mDownTime < 200) {
				float up_degree = detaDegree(x, y);
				Log.i("wmy", "上提时的度数" + up_degree);
				for (int i = 0; i < mShowRooms.size(); i++) {
					if (mShowRooms.get(i).getAngle1() < mShowRooms.get(i)
							.getAngle2()) {
						if ((mShowRooms.get(i).getAngle1() <= up_degree)
								&& ((mShowRooms.get(i).getAngle2() > up_degree) || mShowRooms
										.get(i).getAngle2() == 0)) {
							if (this.listener != null) {
								this.listener.onListener(mShowRooms.get(i)
										.getRoomName(), mShowRooms.get(i)
										.getRoomId(),mRooms.get(i).isSelect());
							}
							mShowRooms.get(i).setSelect(
									!mShowRooms.get(i).isSelect());
							draw();
							break;
						}
					} else {
						if (up_degree < mShowRooms.get(i).getAngle2()
								|| up_degree > mShowRooms.get(i).getAngle1()) {
							if (this.listener != null) {
								this.listener.onListener(mShowRooms.get(i)
										.getRoomName(), mShowRooms.get(i)
										.getRoomId(),mRooms.get(i).isSelect());
							}
							mShowRooms.get(i).setSelect(
									!mShowRooms.get(i).isSelect());
							Log.i("wmy", mShowRooms.get(i).getRoomName());
							draw();
							break;
						}
					}
				}
			}
			// 计算，每秒移动的角度
			float anglePerSecond = mTmpAngle * 1000
					/ (System.currentTimeMillis() - mDownTime);

			// Log.e("TAG", anglePrMillionSecond + " , mTmpAngel = " +
			// mTmpAngle);

			// 如果达到该值认为是快速移动
			if (Math.abs(anglePerSecond) > mFlingableValue && !isFling) {
				// post一个任务，去自动滚动
				post(mFlingRunnable = new AutoFlingRunnable(anglePerSecond));

				return true;
			}

			// 如果当前旋转角度超过NOCLICK_VALUE屏蔽点击
			if (Math.abs(mTmpAngle) > NOCLICK_VALUE) {
				return true;
			}

			break;
		}
		return super.dispatchTouchEvent(event);
	}

	private float getAngle(float xTouch, float yTouch) {
		double x = xTouch - (mRadius / 2d);
		double y = yTouch - (mRadius / 2d);
		return (float) (Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI);
	}

	private int getQuadrant(float x, float y) {
		int tmpX = (int) (x - mRadius / 2);
		int tmpY = (int) (y - mRadius / 2);
		if (tmpX >= 0) {
			return tmpY >= 0 ? 4 : 1;
		} else {
			return tmpY >= 0 ? 3 : 2;
		}

	}

	private void draw() {
		try {
			mCanvas = mHolder.lockCanvas();
			if (mCanvas != null) {
				drawBg();

				float tmpAngle = mStartAngle;
				float sweepAngle = (float) (360 / mItemCount);
				// float sweepAngle = (float)45;
				// .clear();
				for (int i = 0; i < mItemCount; i++) {
					mArcPaint.setColor(0X00000000);
					// MyView myview = new MyView(tmpAngle, tmpAngle +
					// sweepAngle,
					// mDevices.get(i).getName());
					mShowRooms.get(i).setAngle1(tmpAngle);
					mShowRooms.get(i).setAngle2(tmpAngle + sweepAngle);
					// myViews.add(myview);
					mCanvas.drawArc(mRange, tmpAngle, sweepAngle, true,
							mArcPaint);
					drawText(tmpAngle, sweepAngle, mShowRooms.get(i));
					tmpAngle += sweepAngle;
				}
				for (int i = 0; i < mItemCount; i++) {
					Log.i("test", mShowRooms.get(i).getRoomName() + " "
							+ mShowRooms.get(i).getAngle1() + " "
							+ mShowRooms.get(i).getAngle2());
				}

				mStartAngle += mSpeed;

				if (isShouldEnd) {
					mSpeed -= 1;
				}
				if (mSpeed <= 0) {
					mSpeed = 0;
					isShouldEnd = false;
				}
				calInExactArea(mStartAngle);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (mCanvas != null)
				mHolder.unlockCanvasAndPost(mCanvas);
		}

	}

	private void drawBg() {
		mCanvas.drawColor(0xFFFFFFFF);
		mCanvas.drawBitmap(mBgBitmap, null, new Rect(mPadding / 2,
				mPadding / 2, getMeasuredWidth() - mPadding / 2,
				getMeasuredWidth() - mPadding / 2), null);
	}

	public void calInExactArea(float startAngle) {

		float rotate = startAngle + 90;
		rotate %= 360.0;
		for (int i = 0; i < mItemCount; i++) {

			float from = 360 - (i + 1) * (360 / mItemCount);
			float to = from + 360 - (i) * (360 / mItemCount);

			if ((rotate > from) && (rotate < to)) {
				// Log.d("TAG", mStrs[i]);
				return;
			}
		}
	}

	private float detaDegree(float target_x, float target_y) {
		float detaX = target_x - mCenterw;
		float detaY = target_y - mCenterw;
		// Log.i("wmy", "target_x = " + target_x + " target_y = " + target_y
		// + " mCenterw = " + mCenterw);
		double d;
		if (detaX != 0) {
			float tan = Math.abs(detaY / detaX);
			System.out.println(tan);
			if (detaX > 0) {

				if (detaY >= 0) {
					d = Math.atan(tan);

				} else {
					d = 2 * Math.PI - Math.atan(tan);
				}

			} else {
				if (detaY >= 0) {

					d = Math.PI - Math.atan(tan);
				} else {
					d = Math.PI + Math.atan(tan);
				}
			}

		} else {
			if (detaY > 0) {
				d = Math.PI / 2;
			} else {

				d = -Math.PI / 2;
			}
		}

		return (float) ((d * 180) / Math.PI);
	}

	/**
	 * 缁樺埗鍥剧墖
	 * 
	 * @param startAngle
	 * @param sweepAngle
	 * @param i
	 */

	/**
	 * 缁樺埗鏂囨湰
	 * 
	 * @param rect
	 * @param startAngle
	 * @param sweepAngle
	 * @param string
	 */
	// private void drawText(float startAngle, float sweepAngle, String string)
	// {
	private void drawText(float startAngle, float sweepAngle, Room room) {
		Path path = new Path();
		path.addArc(mRange, startAngle, sweepAngle);
		float textWidth;
		if (room.isSelect()) {
			textWidth = mTextPaint1.measureText(room.getRoomName());
		} else {
			textWidth = mTextPaint.measureText(room.getRoomName());
		}
		float hOffset = (float) (mRadius * Math.PI / mItemCount / 2 - textWidth / 2);
		float vOffset = mRadius / 8;
		if (room.isSelect()) {
			mCanvas.drawTextOnPath(room.getRoomName(), path, hOffset, vOffset,
					mTextPaint1);
		} else {
			mCanvas.drawTextOnPath(room.getRoomName(), path, hOffset, vOffset,
					mTextPaint);
		}
	}

	public interface OnListener {
		public void onListener(String name, String id, boolean power);
	}

	private OnListener listener;

	public void setOnListener(OnListener l) {
		this.listener = l;
	}

}
